'''
验证圈定病灶在CT和PET上是否位置正确
将图像和圆形病灶用opencv绘制可视化
观察CT和PET病灶是否绘制在同一个位置

'''


import pydicom
import os
import numpy
from matplotlib import pyplot as plt
import cv2
import pandas as pd
import csv

num = 1
error_list = []


# 提取CT图HU值（-4000，4000），CT图的像素值是由HU值表示的
def get_pixel_hu(slice, patient):
    global num
    image = slice.pixel_array
    # Convert to int16 (from sometimes int16)
    # should be possible as values should always be low enough(<32k)
    image = image.astype(numpy.int16)
    # Set outside-of-scan pixels to 0
    # The intercept is usually -1024,so air is approximately 0
    # CT扫描边界之外的灰度值固定为-2000(dicom和mhd都是这个值)。第一步是设定这些值为0，当前对应为空气（值为0）
    image[image == -2000] = 0

    # Convert to Hounsfield units (HU)
    intercept = slice.RescaleIntercept
    if intercept != -1024:  # 经过统计，有三个病人intercept为0，暂且保留
        error_list.append(patient)
    slope = slice.RescaleSlope
    # print(num, '--->patient：', patient, '--->slope: ', slope, '--->intercept: ', intercept)
    num = num+1
    # print()
    if slope != 1:
        image = slope * image.astype(numpy.float64)
        image = image.astype(numpy.int16)
    image += numpy.int16(intercept)

    return numpy.array(image, dtype=numpy.int16)


# 将输入图像的像素值（-1024，2000）归一化到0-1之间
def normalize_hu(image):
    MIN_BOUND = -1350.0
    MAX_BOUND = 150.0
    image = (image - MIN_BOUND) / (MAX_BOUND - MIN_BOUND)
    image[image > 1] = 1.
    image[image < 0] = 0.
    return image


# 查看一下病人扫描的HU值分布情况:[-2000,2000]
def look_HU(pixels):
    patient_pixels = pixels
    plt.hist(patient_pixels.flatten(), bins=80, color='c')
    plt.xlabel('HU')
    plt.ylabel('Frequence')
    plt.show()


# 可视化归一化后的肺部图像
def visible_dcm(image, img_pt, patient, x, y, r, petx, pety, petr):
    print(patient)
    cv2.circle(image, (x, y), r, (0, 0, 0))
    cv2.circle(img_pt, (petx, pety), petr, (0, 0, 0))
    cv2.imshow('CT', image)
    cv2.imshow('PET', img_pt)
    cv2.waitKey()
    cv2.destroyAllWindows()



def process_dcm():
    src_path = 'D:/lung_cancer/data/all_data3.csv'
    f = csv.reader(open(src_path, 'r'))
    data = []
    for i in f:
        data.append(i)

    for line in data[200:]:
        patient = line[1]
        CT_PATH = 'D:/lung_cancer/data/'+line[35]
        image_ct = numpy.load(CT_PATH)

        PET_PATH = 'D:/lung_cancer/data/'+line[34]
        image_pet = numpy.load(PET_PATH)
        print('%s pet max pixel %d' % (patient,numpy.max(image_pet)))
        img_pt = 1 - (image_pet) / numpy.float(numpy.max(image_pet))

        x = int(line[3])
        y = int(line[4])
        r = int(line[5])
        petx = int(line[36])
        pety = int(line[37])
        petr = int(line[38])
        visible_dcm(image_ct, img_pt, patient, x, y, r, petx, pety, petr)


if __name__ == '__main__':
    process_dcm()